/*
 * PollExample.c
 *
 *  Created on: 2013年5月16日
 *      Author: drowning
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/poll.h>
#include <sys/types.h>
#include <signal.h>

#ifndef POLLEXAMPLE_C_
#define POLLEXAMPLE_C_

#define BUF_SIZE 200
#define MYPORT 1234
#define QNUM 10

void RunPollServer() {
	int sock_fd; // listen on sock_fd, new connection on new_fd
	struct sockaddr_in server_addr; // server address information
	struct sockaddr_in client_addr; // connector's address information
	int yes = 1;

	char buf[BUF_SIZE];

	if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
		perror("setsockopt");
		exit(1);
	}

	server_addr.sin_family = AF_INET; // host byte order
	server_addr.sin_port = htons(MYPORT); // short, network byte order
	server_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
	memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));

	if (bind(sock_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {
		perror("bind");
		exit(1);
	}

	if (listen(sock_fd, QNUM) == -1) {
		perror("listen");
		exit(1);
	}

	printf("listen port %d\n", MYPORT);

	/*pollfd结构
	 * 1.文件描述符
	 * 2.需要poll监听的时间可以用|来监听多个事件 比如 POLLIN|POLLPRI
	 * 3.poll监听到时间之后返回事件码(POLLIN)
	 * 判断 (revents & POLLIN ) == events
	 */
	struct pollfd pollfd_A[QNUM];
	int i;
	for (i = 0; i < QNUM; i++) {
		pollfd_A[i].fd = -1;
	}
	pollfd_A[0].fd = sock_fd;
	pollfd_A[0].events = POLLIN ;
	socklen_t client_len = sizeof(client_addr);
	while (1) {
		//参数：pollfd数组指针 , 一共多少文件描符 , 如果没有数据阻塞多久(毫秒)
		int size = poll(pollfd_A, QNUM, 40000);
		if (size == 0) {
			printf("poll timeout");
			continue;
		} else if (size > 0) {
			if ( (pollfd_A[0].revents & POLLIN ) == pollfd_A[0].events) {
				int ret = accept(sock_fd, (struct sockaddr *)&client_addr, &client_len);
				if (ret > 0) {
					for (i = 0; i < QNUM; i++) {
						if (pollfd_A[i].fd == -1) {
							pollfd_A[i].fd = ret;
							pollfd_A[i].events = POLLIN ;
							break;
						}
					}
				} else {
					printf("accept error");
				}
			} else {
				//check pollfd_A 中是否有数据到达
				for (i = 0; i < QNUM; i++) {
					printf("\n %d" , pollfd_A[i].fd);
					if ( (pollfd_A[i].revents & POLLIN ) == pollfd_A[i].events && pollfd_A[i].fd != -1) {
						int f = recv(pollfd_A[i].fd, buf, 1024, 0);
						if (f <= 0) {
							printf("closing the fd");
							int close_fd= pollfd_A[i].fd;
							close(close_fd);
							pollfd_A[i].fd = -1;
						} else {
							buf[f] = '\0';
							printf("from client msg: %s ", buf);
						}
					}
				}
			}
		}
	}
}

#endif /* POLLEXAMPLE_C_ */
